package com.nhim.cms.admin.client.eldf.ui;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.nhim.cms.admin.shared.ElementDefinitionProxy;

public class ElementTypeTextBox extends Composite implements IElementType {

	private static ElementTypeTextBoxUiBinder uiBinder = GWT
			.create(ElementTypeTextBoxUiBinder.class);

	interface ElementTypeTextBoxUiBinder extends
			UiBinder<Widget, ElementTypeTextBox> {
	}

	public ElementTypeTextBox() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiField
	TextBox txtMaxLength;
	@UiField
	TextBox txtDefaultValue;
	@UiField
	CheckBox chkAllowEdit;

	public ElementTypeTextBox(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));

	}

	private Boolean isNumber(String s) {
		if (!s.isEmpty()) {
			try {
				Integer value = Integer.parseInt(s);
				if (value <= 0)
					return false;
			} catch (NumberFormatException e) {
				return false;
			}
		}
		return true;

	}

	public List<String> validate() {
		List<String> validation = new ArrayList<String>();
		if (!isNumber(this.txtMaxLength.getText())) {
			validation.add("Invalid number format for Maximum Length.");
		}
		return validation;
	}

	public void save(ElementDefinitionProxy element) {
		element.setAllowEdit(this.chkAllowEdit.getValue());
		element.setDefinitionText(this.txtMaxLength.getValue());
		element.setDefaultValue(this.txtDefaultValue.getValue());

	}

	public void setData(ElementDefinitionProxy element) {
		if (element != null) {
			this.txtMaxLength.setText(element.getDefinitionText());
			this.txtDefaultValue.setText(element.getDefaultValue());
			this.chkAllowEdit.setValue(element.getAllowEdit());
		} else {
			this.txtMaxLength.setText("");
			this.txtDefaultValue.setText("");
			this.chkAllowEdit.setValue(true);

		}

	}

}
